package com.itheima.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.controller.results.Code;
import com.itheima.controller.results.Result;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.system.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping
    public Result save(User user){
        boolean save = userService.save(user);
        return new Result(save ? Code.SAVE_OK:Code.SAVE_ERROR);
    }

    @PutMapping
    public Result update(User user){
        boolean update = userService.update(user);
        return new Result(update?Code.UPDATE_OK:Code.UPDATE_ERROR);
    }

    @DeleteMapping("/{uuid}")
    public Result delete(@PathVariable Integer uuid){
        boolean delete = userService.delete(uuid);
        return new Result(delete?Code.DELETE_OK:Code.DELETE_ERROR);
    }
    @PostMapping("/login")
    public Result login(String username,String password){
        User user = userService.login(username, password);
        return new Result(null != user ?Code.FIND_OK: Code.FIND_ERROR,user);
    }

    @GetMapping("/{uuid}")
    public Result findById(@PathVariable Integer uuid){
        User user = userService.findById(uuid);
        //模拟出现异常，使用条件控制，便于测试结果
        if (uuid == 2) throw new BusinessException("查询出错啦",Code.FIND_ERROR);
        return new Result(null !=user ? Code.FIND_OK: Code.FIND_ERROR,user);
    }

    @GetMapping("/{page}/{size}")
    public Result getAll(@PathVariable Integer page, @PathVariable Integer size){
        PageInfo<User> user = userService.findAll(page, size);
        return new Result(null !=user ? Code.FIND_OK:Code.FIND_ERROR,user);
    }

}
